package data;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * This class sorts a list of Items by its contents' similarities to a search
 * query
 * 
 * @author Stephen
 * 
 */

public class ItemsSortByQuery {

	/** The query string that will be searched **/
	private String query;

	/**
	 * Creates an ItemSortByQueryClass
	 * 
	 * @param query
	 *            - the query string to search with
	 */
	public ItemsSortByQuery(String query) {
		this.query = query;
	}

	/**
	 * Sorts the items by their similarity to the Search query. Sorts in
	 * ascending order
	 * 
	 * @param items
	 *            - the item list to sort
	 */
	public void sort(List<Item> items) {
		final Sentence querySentence = new Sentence(query);

		Collections.sort(items, new Comparator<Item>() {
			@Override
			public int compare(Item item1, Item item2) {
				Sentence s1 = itemSentence(item1);
				Sentence s2 = itemSentence(item2);

				return querySentence.similarWordCount(s2)
						- querySentence.similarWordCount(s1);
			}
		});

	}

	/**
	 * Returns a Sentence constructed out of the given Item's details.
	 * 
	 * @param item
	 *            - the Item to construct the sentence from
	 * @return - a Sentence corresponding to the given Item's details
	 */
	private Sentence itemSentence(Item item) {
		String buff = "";
		buff = item.getName() + " " + item.getDescription() + " "
				+ item.getLocation() + " " + item.getAccountName() + " ";
		return new Sentence(buff);

	}
}
